﻿using System.Collections.Generic;
using LinkPad.Helpers;
using LinkPad.Shapes;
using Windows.Foundation;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;

namespace LinkPad.Handlers
{
    class Eraser : CanvasActionHandler
    {
        #region Fields

        private readonly ShapeManager _shapeManager;

        #endregion

        #region Constructors

        public Eraser(ShapeManager shapeManager)
            : base(shapeManager)
        {
            _shapeManager = shapeManager;
        }

        #endregion

        #region Methods

        #region CanvasActionHandler members

        protected override void Attach()
        {
            base.Attach();
            MyCanvas.Tapped += HandleTapped;
        }

        protected override void Detach()
        {
            base.Detach();
            MyCanvas.Tapped -= HandleTapped;
        }

        #endregion

        private void HandleTapped(object sender, TappedRoutedEventArgs e)
        {
            var pos = e.GetPosition(MyCanvas);

            // TODO optimise this
            foreach (var child in MyCanvas.Children)
            {
                var x = (double)child.GetValue(Canvas.LeftProperty);
                var y = (double)child.GetValue(Canvas.TopProperty);

                var tb = child as TextBlock;
                if (tb != null)
                {
                    var w = tb.ActualWidth;
                    var h = tb.ActualHeight;
                    var rect = new Rect(x, y, w, h);
                    if (rect.Contains(pos))
                    {
                        MyCanvas.Children.Remove(tb);
                    }
                }
            }

            // composite shapes
            var shapesToRemove = new List<IManagedShape>();
            foreach (var shape in _shapeManager.Shapes)
            {
                var boundingBox = shape.BoundingBox;
                var diagonal = boundingBox.DiagonalLength();
                var margin = diagonal*0.05;
                var erx = 2*margin/boundingBox.Width + 1;
                var ery = 2*margin/boundingBox.Height + 1;
                var expandedBoundingBox = boundingBox.ExpandRect(erx, ery);
                if (!expandedBoundingBox.Contains(pos))
                {
                    continue;
                }
                var dist = shape.DistanceToPoint(pos);
                if (dist < margin)
                {
                    shapesToRemove.Add(shape);
                }
            }
            foreach (var shape in shapesToRemove)
            {
                _shapeManager.RemoveShape(shape);
            }

            // simple shapes
        }


        #endregion
    }
}
